# -*- coding: utf-8 -*-
"""
Module Description: 头像称号变更方法
Date: 2018/12/04
Author: chenmurong
"""
from pyshare.dal.repository_impl import RoleRepository, ItemRepository
from pyshare.dal.gameconfig.query import getProfileList
from pyshare.framework.dal.dal_manager import TransactionDelegator
from pyshare.utils import push_utils
from pyshare.const.enums.item import ItemType, HeadPushStatus
from pyshare.distributed.area_lock_define import RoleLock as RoleBehaviorLock
import pyshare.framework.distribute.mutex as mutex


class HeadManager(object):
    """
    限时头像管理--活动榜单
    """
    def __init__(self, field, value, new_owner_rid=None, cfg_list=None):
        self.head_cfg_list = cfg_list if cfg_list else getProfileList('TcItemHead', **{field: value})

        if not self.head_cfg_list:
            return

        for cfg in self.head_cfg_list:
            if cfg.Sex == 1:
                self.male_head_id = cfg.ItemId
            else:
                self.female_head_id = cfg.ItemId

        self.head_id_list = [self.male_head_id, self.female_head_id]
        self.new_head = None
        self.old_head = None
        self.old_owner_rid = None
        self.new_owner_rid = new_owner_rid

    def is_need_change(self):
        """检测是否需要变换拥有者"""
        return False if not self.head_cfg_list else True

    def return_head_id(self, sex):
        return self.male_head_id if sex == 1 else self.female_head_id

    @staticmethod
    def push_head(small_head_id, sex, rid):
        """
        当前小头像推送
        :param clothes_id: 小头像id
        :param sex: 性别
        :param rid: 角色id
        :return:
        """
        push_utils.call_push_data(
            push_id=push_utils.PushId.NOW_SMALL_HEAD_ID,
            data={
                "SmallHeadId": small_head_id,
                "Sex": sex
            },
            send_rid_list=[rid]
        )

    @staticmethod
    def push_head_change(small_head_id, rid, status_type):
        """
        小头像变更推送
        :param small_head_id: 小头像id
        :param rid: 角色id
        :param status_type: 头像变更情况 enum HeadPushStatus
        :return:
        """
        push_utils.call_push_data(
            push_id=push_utils.PushId.SMALL_HEAD_ID_CHANGE,
            data={
                "ItemType": ItemType.Head,
                "ItemId": small_head_id,
                "GetFlag": status_type
            },
            send_rid_list=[rid]
        )

    def create_new_head(self, role=None, check_first=False):
        """创建头像记录"""
        role = role if role else RoleRepository.get_by_rid(self.new_owner_rid)
        self.new_head = self.return_head_id(role.sex)
        if check_first and ItemRepository.get_by_rid_itemtype_itemid(
                rid=self.new_owner_rid, item_type=ItemType.Head, item_id=self.new_head):
            return
        ItemRepository.create(rid=self.new_owner_rid,
                              item_type=ItemType.Head,
                              item_id=self.new_head,
                              count=1)

    @staticmethod
    def get_default_head_id(sex):
        # 免费
        c_cfg_list = getProfileList('TcItemHead', IsFree=1, Sex__in=[sex, 2], order_by='ItemId')
        return c_cfg_list[0].ItemId

    def change_old_owner_head(self):
        """修改 old owner 默认头像"""
        with mutex.KeyMutex(RoleBehaviorLock.G_ROLE_MODIFY_HEAD_LOCK.format(RoleGuid=self.old_owner_rid)):
            old_role = RoleRepository.get_by_rid(self.old_owner_rid)
            # 佩戴的小头像是需要更换的
            if old_role and old_role.small_head_id == self.old_head:
                old_role.small_head_id = self.get_default_head_id(old_role.sex)
                RoleRepository.save(old_role)
                self.push_head(old_role.small_head_id, old_role.sex, self.old_owner_rid)
            self.push_head_change(self.old_head, self.old_owner_rid, HeadPushStatus.Lost)

    def new_owner(self, first_rid=None, role=None, is_push=False):
        """
        新拥有者处理
        :param first_rid: 第一名
        :param role: 角色适配器实例
        :param is_push: 是否推送消息
        :return: 是否变更
        """
        self.new_owner_rid = first_rid if first_rid else self.new_owner_rid
        with ItemRepository.lock(ItemType=ItemType.Head, ItemId=self.male_head_id):
            with ItemRepository.lock(ItemType=ItemType.Head, ItemId=self.female_head_id):
                with TransactionDelegator():
                    head = ItemRepository.get_by_itemtype_itemid_list(item_type=ItemType.Head,
                                                                      item_id_list=self.head_id_list)
                    if head:
                        self.old_head = head.item_id
                        self.old_owner_rid = head.role_guid
                        if head.role_guid == self.new_owner_rid:
                            return False
                        ItemRepository.delete(head)

                    self.create_new_head(role=role)
        if is_push:
            # 小头像推送
            self.push_head_change(self.new_head, self.new_owner_rid, HeadPushStatus.Get)
        return True

    def old_owner(self):
        """
        上一个拥有者处理
        :return:
        """
        if self.old_owner_rid and self.old_owner_rid != self.new_owner_rid:
            self.change_old_owner_head()
